<template>
  <div class="add-goods">
      <van-nav-bar title="添加商品" left-arrow @click-left="back()" />
    <div class="store-pic">
      <div class="goods-text hc-goods-header">
        <span>商品封面</span>
        <i>(1:1图片)</i>
      </div>
      <div class="right-pic">
        <div class="bot-upload">
          <van-uploader v-model="goodsImg" :before-read="beforeRead" @delete="deleteFile" accept="image/*" :max-count="1" image-fit="contain" preview-size='1.6rem' />
        </div>
      </div>
    </div>
    <!-- 商品名称 -->
    <div class="goods-name">
      <div class="goods-text">
        <span>商品名称</span>
      </div>
      <div class="mid">
        <van-cell-group>
          <van-field style="width:5rem;" v-model="goodsData.title" placeholder="请输入商品名称" />
        </van-cell-group>
      </div>
    </div>
    <!--  -->
    <div class="goods-name" @click="showPicker = true">
      <div class="goods-text">
        <span>活动类型</span>
      </div>
      <div class="mid">
        <van-cell-group>
          <van-field style="width:5rem;" readonly v-model="goodsData.typeText" placeholder="请选择商品活动类型" />
        </van-cell-group>
      </div>
    </div>
    <!-- 价格 -->
    <div class="goods-name">
      <div class="goods-text">
        <span>价　　格</span>
      </div>
      <div class="mid">
        <van-cell-group>
          <van-field type="number" style="width:5rem;" v-model="goodsData.price" placeholder="请输入商品价格" />
        </van-cell-group>
      </div>
    </div>
    <!-- 原价 -->
    <div class="goods-name">
      <div class="goods-text">
        <span>原　　价</span>
      </div>
      <div class="mid">
        <van-cell-group>
          <van-field type="number" style="width:5rem;" v-model="goodsData.old_price" placeholder="请输入商品原价" />
        </van-cell-group>
      </div>
    </div>
    <!-- <div class="goods-name">
      <div class="goods-text">
        <span>状　　态</span>
      </div>
      <div class="mid">
        <van-radio-group v-model="goodsData.goodsStatus" direction="horizontal">
          <van-radio  checked-color="#07c160" shape="square" name="1">在售</van-radio>
          <van-radio  checked-color="#07c160" shape="square" name="2">下架</van-radio>
        </van-radio-group>
      </div>
    </div> -->
    <!-- 规格 -->
    <!-- <div class="goods-name">
      <div class="goods-text">
        <span>规　　格</span>
      </div>
      <div class="mid">
        <van-cell-group>
          <van-field style="width:5rem;" v-model="specs" placeholder="请输入商品规格" />
        </van-cell-group>
      </div>
    </div> -->
    <!-- 商品简介 -->
    <div class="store-introduce">
      <div class="goods-text">
        <span>商品介绍</span>
      </div>
      <div class="inpro-text">
        <van-cell-group>
          <van-field style="width:5.3rem" v-model="goodsData.content" rows="6" autosize type="textarea" placeholder="请输入商品简介" />
        </van-cell-group>
      </div>
    </div>

    <div class="store-pic" style="padding-bottom: 10px;">
      <div class="goods-text hc-goods-header">
        <span>商品图片</span>
        <i>(3:2图片)</i>
      </div>
      <div class="right-pic">
        <div class="bot-upload">
          <van-uploader v-model="goodspic" :before-read="beforeReadGoods" @delete="deleteFileGoods" accept="image/*" :max-count="9" />
        </div>
      </div>
    </div>
    <div class="goods-name">
      <div class="goods-text">
        <span>规　　格</span>
      </div>
      <div class="mid">
        <van-button type="primary" size="mini" @click="handlerAddSpec">添加</van-button>
      </div>
    </div>
    <div style="margin-bottom: 100px;padding: 5px 20px 0">
      <div class="hc-spec-box" v-for="(item, index) in specsList" :key="index">
        <div @click="handlerDelSpec(index)" class="hc-remove-spec">
          <van-icon class="hc-remove-spec-icon" color="#f00" size="30px" name="clear" />
        </div>
        <van-cell-group>
           <van-field :border="false" placeholder="请输入规格名称" v-model="item.name" type="text" label="规格名称：" />
           <van-field :border="false" placeholder="请输入规格价格" v-model="item.price" type="tel" label="规格价格：" />
           <van-field name="uploader"  label="图片上传：">
            <template #input>
              <van-uploader v-model="item.preImage" accept="image/*" :max-count="1" @delete="() => { deleteFileSpec(index) }" :before-read="(file) => {beforeReadSpec(index, file)}"/>
            </template>
          </van-field>
        </van-cell-group>
      </div>
    </div>
    <div style="padding-top: 100px;visibility: hidden;">
    </div>
    <div class="btn-submit" style="background: #07c160" :class="goodsData.id ? 'has-del' : ''" @click="handlerSubmit">
      提交
    </div>
    <div v-if="goodsData.id" class="btn-del">
        <van-col @click="handlerDel(0)" v-if="goodsData.id && goodsData.status === 2" style="background: #1989fa" class="van-hairline--right" span="12">上架</van-col>
        <van-col @click="handlerDel(2)" v-if="goodsData.id && goodsData.status === 0" style="background: #ff976a" class="van-hairline--right" span="12">下架</van-col>
        <van-col @click="handlerDel(3)" style="background: #ee0a24" span="12">删除</van-col>
    </div>
    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        :columns="['无', '限时购', '清仓']"
        @confirm="onConfirm"
        @cancel="showPicker = false"
      />
    </van-popup>
  </div>
</template>

<script>
import { postUpload, postAddGoods, postGetGoodsInfo, postEditGoods, changeGoodsStatus } from '../../api/ajax'
import { HcMessageBox } from '../../components/hcMessage/index.js'
import { Dialog } from 'vant';
export default {
  data() {
    return {
      username: '',
      price: "",
      before_price: '',
      specs: '',
      introduce: '',
      goodspic: [],
      goodsImg: [],
      showPicker: false,
      goodsData: {
        title: '',
        price: '',
        img: '',
        old_price: '',
        content: '',
        image_list: '',
        image_list_arr: [],
        type: 0,
        typeText: '无',
        goodsStatus: '1'
      },
      specsList: []
    }
  },
  methods: {
    handlerAddSpec() {
      this.specsList.push({
        "name": "", //规格名
        "price": '',  //规格价格
        "image": '',  //规格图片
        "preImage": []
      })
    },
    handlerDelSpec(index) {
      this.specsList.splice(index, 1)
    },
    onConfirm(val, index) {
      this.goodsData.typeText = val;
      this.goodsData.type = index;
      this.showPicker = false;
    },
    handlerSubmit() {
      let params = { ...this.goodsData };
      params.image_list = params.image_list_arr.join(',');

      console.log(this.specsList)
      let isSpecFlag = false;
      this.specsList.forEach(item => {
        if(!item.name || !item.price || !item.image) {
          isSpecFlag = true
        }
      })
      if(isSpecFlag) {
        this.$toast('请完善商品规格')
        return;
      }
      if(!params.img) {
        this.$toast('请上传商品封面')
      }else if(!params.title) {
        this.$toast('请输入商品名称')
      }else if(!params.price) {
        this.$toast('请输入商品价格')
      }else if(!params.old_price) {
        this.$toast('请输入商品原价')
      }else if(!params.content) {
        this.$toast('请输入商品介绍')
      }else if(!params.image_list) {
        this.$toast('请上传商品图片')
      }else {
        console.log(this.specsList)
        let option_json = [];
        this.specsList.forEach(item => {
          option_json.push({
            name: item.name,
            price: item.price,
            image: item.image
          })
        })
        params.option_json = JSON.stringify(option_json)
        this.postAddGoods(params);
      }
      console.log(params);
    },
    handlerDel(status) {
      let tempObj = {
        '0': '上架',
        '2': '下架',
        '3': '删除',
      }
      Dialog.confirm({
        title: '提示',
        message: `确定${tempObj[status]}该商品吗？`,
        confirmButtonColor: '#07c160',
        closeOnClickOverlay: true
      }).then(async () => {
        const result = await changeGoodsStatus({
          goods_id: this.goodsData.id,
          status
        })
        if(result.code == 1) {
          HcMessageBox(`${tempObj[status]}成功！`)
          setTimeout(() => {
            this.back()
            HcMessageBox.close();
          }, 1000)
        }
      });
    },
    async postAddGoods(params) {
      let result = {}
      if(this.$route.query.type === 'edit') {
        params.goods_id = params.id
        result = await postEditGoods(params);
      }else {
        result = await postAddGoods(params);
      }
      if(!!result && result.code === 1) {
        HcMessageBox('操作成功');
        setTimeout(() => {
          this.back()
          HcMessageBox.close();
        }, 1000)
      }
    },
    beforeReadGoods(file) {
      return new Promise((resolve, reject) => {
        this.postUpload(file, (result) => {
          if(result.code == 1) {
            this.goodsData.image_list_arr.push(result.id);
            resolve(true);
          }else {
            reject(false);
          }
        });
      })
    },
    deleteFileGoods(file, { index }) {
      this.goodsData.image_list_arr.splice(index, 1);
    },
    beforeRead(file) {
      return new Promise((resolve, reject) => {
        this.postUpload(file, (result) => {
          if(result.code == 1) {
            this.goodsData.img = result.id
            resolve(true);
          }else {
            reject(false);
          }
        });
      })
    },
    beforeReadSpec(index, file) {
      return new Promise((resolve, reject) => {
        this.postUpload(file, (result) => {
          if(result.code == 1) {
            this.specsList[index].image = result.id;
            this.specsList[index].preImage = [
              {url: this.publicUrl + result.src}
            ]
            resolve(true);
          }else {
            reject(false);
          }
        });
      })
    },
    deleteFile() {
      this.goodsData.img = '';
    },
    deleteFileSpec(index) {
      this.specsList[index].image = '';
    },
    async postUpload(file, cb) {
      let form = new FormData();
      form.append('file', file);
      const result = await postUpload(form, { contentType: 'multipart/form-data' })
      if (result) {
        cb && cb(result)
      }
    },
    async postGetGoodsInfo() {
      const {img_list, info, option_list} = await postGetGoodsInfo({
        goods_id: this.$route.query.id
      })
      this.specsList = [];
      option_list && option_list.forEach(item => {
        this.specsList.push({
          id: item.id,
          name: item.name,
          price: item.price,
          image: item.image,
          preImage: [{
            url: this.publicUrl + item.filepath
          }]
        })
      })
      console.log(this.specsList)
      this.goodsData = {
        ...this.goodsData,
        ...info
      }
      if(this.goodsData.type === 0) {
        this.goodsData.typeText = '无'
      }else if(this.goodsData.type === 1) {
        this.goodsData.typeText = '限时'
      }else if(this.goodsData.type === 2) {
        this.goodsData.typeText = '清仓'
      }
      this.goodsImg = [{
        url: this.publicUrl + info.filepath
      }]
      img_list.forEach(item => {
        this.goodspic.push({
          url: this.publicUrl + item.filepath
        })
        this.goodsData.image_list_arr.push(item.id)
      })
      console.log(this.goodsData)
    }
  },
  mounted() {
    if(this.$route.query.type === 'edit') {
      this.postGetGoodsInfo();
    }
  }
}
</script>

<style lang="scss" scoped>
.add-goods {
  padding-bottom: px2rem(40);
}
.hc-spec-box {
  padding: 10px;
  background-color: #fff;
  box-shadow: 0 0 1px rgba($color: #000000, $alpha: .5);
  border-radius: 10px;
  margin-bottom: 10px;
  margin-top: 10px;
  position: relative;
  .hc-remove-spec {
    position: absolute;
    right: 0px;
    top: 0px;
    transform: translateX(30%) translateY(-30%);
    z-index: 10;
  }
}
.goods-name {
  height: px2rem(50);
  border-bottom: px2rem(2) #f4f4f4 solid;
  .input-name {
    float: left;
    width: 70%;
    height: 100%;
    padding-left: px2rem(11);
  }
}
.mid {
  float: left;
  width: 70%;
  height: px2rem(50);
  display: flex;
  align-items: center;
}
.store-introduce {
  height: px2rem(170);
  border-bottom: px2rem(10) #f5f5f5 solid;
  .inpro-text {
    float: left;
    height: px2rem(170);
    background-color: #fff;
    overflow-y: scroll;
  }
}
.goods-text {
  float: left;
  width: 25%;
  font-size: px2rem(16);
  // font-weight: bold;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  &.hc-goods-header {
    height: px2rem(80);
    i {
      font-style: normal;
      font-size: 12px;
      font-weight: 300;
      color: #999;
      padding-top: 4px;
    }
  }
}

.btn-submit {
  height: px2rem(40);
  background-color: #fd7a29;
  text-align: center;
  line-height: px2rem(40);
  font-size: px2rem(16);
  color: #fff;
  position: fixed;
  bottom: 0;
  width: 100%;
  z-index: 1000;
  &.has-del {
    bottom: px2rem(40)
  }
}
.btn-del {
  background-color: #fff;;
  height: px2rem(40);
  text-align: center;
  line-height: px2rem(40);
  font-size: px2rem(16);
  color: #fff;
  position: fixed;
  bottom: 0;
  width: 100%;
}

.store-pic {
  padding-top: px2rem(10);
  overflow: hidden;
  .right-pic {
    float: left;
    width: 71%;
    padding-left: px2rem(11);
    // height: px2rem(170);
    // background-color: red;
    .top-text {
      height: px2rem(50);
      line-height: px2rem(50);
      font-size: px2rem(14);
      color: #a6a6a6;
    }
  }
}
</style>
